package com.mo.tools.bean;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @name: ApplicationContextHolder
 * @description: SpringContext上下文
 * @author: Yang Xingfu
 * @date: 2020-01-09 09:58
 **/

@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    /**
     * Spring上下文处理对象
     */
    private static ApplicationContext applicationContext;


    /**
     * 设置applicationContext对象
     * @param applicationContext spring上下文
     * @throws BeansException 异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    /**
     * 获取spring 上下文对象
     * @return applicationContext对象
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * spring上下文中注入的对象
     * @param name spring配置文件中配置的bean名或注解的名称
     * @param <T> 泛型
     * @return  容器中的对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        try {
            return (T) applicationContext.getBean(name);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * spring上下文中注入的对象
     * @param clazz 类型注册的bean的实例
     * @param <T> 泛型
     * @return  容器中的对象
     */
    public static <T> T getBean (Class<T> clazz) {
        try {
            return applicationContext.getBean(clazz);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * ioc容器中是否存在这个bean对象
     * @param name ioc容器中注册的bean名称
     * @return 存在返回true否则返回false
     */
    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }
}
